#include <iostream>
#include <memory>
#include <sys/epoll.h>
#include "Log.hpp"
#include "Socket.hpp"

using namespace SocketModule;
using namespace LogModule;

class EpollServe
{
    const static int size = 64;
    const static int defaultfd = -1;

public:
    EpollServe(int port)
        : _listen_sock(std::make_unique<TcpSocket>()), _isrunning(false), _epfd(defaultfd)
    {
        _listen_sock->BulidListenSocketMethod(port);
        // 创建epoll模型
        _epfd = epoll_create(256);
        if (_epfd < 0)
        {
            LOG(LogLevel::ERROR) << "epoll error";
            exit(EPOLL_CREAT_ERROR);
        }
        LOG(LogLevel::INFO) << "Epoll success..." << _epfd;

        // accept之前把listen套接字添加进入epoll模型的红黑树里，这样accept的时候就可以非阻塞式直接accept
        struct epoll_event ev;
        ev.events = EPOLLIN;
        ev.data.fd = _listen_sock->Fd();
        int n = epoll_ctl(_epfd, EPOLL_CTL_ADD, _listen_sock->Fd(), &ev);
        if (n < 0)
        {
            LOG(LogLevel::ERROR) << "epool listensock add error ";
        };
    };
    ~EpollServe()
    {
        _listen_sock->Close();
        if (_epfd > 0)
            close(_epfd);
    };

    void Start()
    {
        int timeout = -1;
        _isrunning = true;
        while (_isrunning)
        {
            int n = epoll_wait(_epfd, _revs, size, timeout);
            switch (n)
            {
            case 0:
                LOG(LogLevel::INFO) << "TIMEOUT...";
                break;
            case -1:
                LOG(LogLevel::ERROR) << "epoll_wait error...";
                break;
            default:
                Dispatcher(n);
                break;
            }
        }
        _isrunning = false;
    }

    void Dispatcher(int rnum)
    {
        LOG(LogLevel::INFO) << "event ready....";
        for (int i = 0; i < rnum; i++)
        {
            // 读事件
            int revent = _revs->events;
            auto sockfd = _revs->data.fd;
            if (revent & EPOLLIN)
            {
                if (sockfd == _listen_sock->Fd())
                {
                    Accepter();
                }
                else
                {
                    Recver(sockfd);
                }
            }
        }
    }

private:
    std::unique_ptr<Socket> _listen_sock;
    bool _isrunning;
    int _epfd;

    struct epoll_event _revs[size];

public:
    void IsStop() { _isrunning = false; }
    void Accepter()
    {
        InetAddr client;
        int sockfd = _listen_sock->Accept(&client);
        if (sockfd > 0)
        {
            struct epoll_event ev;
            ev.events = EPOLLIN;
            ev.data.fd = sockfd;
            int n = epoll_ctl(_epfd, EPOLL_CTL_ADD, sockfd, &ev);
            if (n < 0)
            {
                LOG(LogLevel::ERROR) << "epool normol add error ";
            };
        }
    }

    void Recver(int sockfd)
    {
        char buffer[1024];
        ssize_t n = recv(sockfd, buffer, sizeof(buffer) - 1, 0);
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << buffer << std::endl;
        }
         else if (n == 0)
        {
            LOG(LogLevel::INFO) << "client quit....";
            int m=epoll_ctl(_epfd,EPOLL_CTL_DEL,sockfd,nullptr);
            if(m>0)
            {

            }
            close(sockfd);
        }
        else
        {
            LOG(LogLevel::INFO) << "recv error....";
            int m=epoll_ctl(_epfd,EPOLL_CTL_DEL,sockfd,nullptr);
            if(m>0)
            {

            }
            close(sockfd);
        }
    }
    // {
    //
    //
    //
    //    
    //         
    //          close(_fds[pos].fd);
    //         _fds[pos].fd = defaultfd;
    //         _fds[pos].events = 0;

    //  /   }
    //     else
    //     {
    //         LOG(LogLevel::ERROR) << "recv error....";
    //     }
    // }
};